# Purpose: Configures application logging based on a YAML file.
# Changes:
# - No major functional changes from the previous correct version.
# - Ensured paths are calculated correctly relative to this file's location.
# - Added basic console logging as an immediate fallback if file loading fails.

import logging
import logging.config
import yaml
import os
from pathlib import Path

# Assume this file is at src/core/logging_setup.py
# Project Root is Path(__file__).parent.parent.parent
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent
DEFAULT_LOG_CONFIG_PATH = PROJECT_ROOT / "config" / "logging.yaml"
LOGS_DIR = PROJECT_ROOT / "logs" # Default logs directory

_logging_initialized = False

def setup_logging_from_config(config_path: Path = DEFAULT_LOG_CONFIG_PATH) -> None:
    """
    Sets up logging configuration from a YAML file. Ensures it only runs once.
    Interprets log file paths relative to the project root and ensures directories exist.

    Args:
        config_path: Path to the logging configuration YAML file.
    """
    global _logging_initialized
    if _logging_initialized:
        # Use logging.log to avoid issues if root logger level is high
        logging.log(logging.DEBUG, "Logging already initialized, skipping setup.")
        return

    # Ensure base logs directory exists (optional, config can specify full paths too)
    try:
        LOGS_DIR.mkdir(parents=True, exist_ok=True)
    except OSError as e:
         # Log to console if directory creation fails
         print(f"WARNING: Could not create base log directory {LOGS_DIR}: {e}")

    if config_path.exists():
        try:
            with open(config_path, 'rt', encoding='utf-8') as f:
                log_config_dict = yaml.safe_load(f.read())

            # Ensure log directories specified in handlers exist and update paths
            if 'handlers' in log_config_dict:
                for handler_name, handler_config in log_config_dict['handlers'].items():
                    if 'filename' in handler_config:
                        # Assume filename in YAML is relative to project root
                        relative_log_path = Path(handler_config['filename'])
                        # Make path absolute relative to project root if not already absolute
                        if not relative_log_path.is_absolute():
                            log_file_path = PROJECT_ROOT / relative_log_path
                            try:
                                # Ensure the log file's directory exists
                                log_file_path.parent.mkdir(parents=True, exist_ok=True)
                                # Update the config dict with the absolute path string
                                handler_config['filename'] = str(log_file_path)
                                # Use print for early stage logging before config is applied
                                print(f"DEBUG: Log file path set for handler '{handler_name}': {log_file_path}")
                            except OSError as e:
                                 print(f"WARNING: Failed to create log directory {log_file_path.parent} for handler '{handler_name}': {e}")
            else:
                 print("WARNING: 'handlers' section not found in logging config.")


            logging.config.dictConfig(log_config_dict)
            _logging_initialized = True
            logging.info(f"Logging configured successfully from {config_path}")

        except Exception as e:
            # Fallback to basic console config if loading/parsing fails
            logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(name)s - %(message)s")
            logging.exception(f"Error loading logging configuration from {config_path}. Using basic console logging.")
            _logging_initialized = True # Mark as initialized even on failure
    else:
        # Fallback to basic console config if file doesn't exist
        logging.basicConfig(level=logging.INFO, format="%(levelname)s - %(name)s - %(message)s")
        logging.warning(f"Logging configuration file not found at {config_path}. Using basic console logging.")
        _logging_initialized = True

def get_logger(name: str) -> logging.Logger:
    """Gets a logger instance, ensuring setup runs at least once."""
    if not _logging_initialized:
        # This might be called before explicit setup in some cases
        print("WARNING: Logger requested before explicit logging setup. Running setup now.")
        setup_logging_from_config()
    return logging.getLogger(name)